package com.study.banyiyi.controller;

import com.mysql.cj.util.StringUtils;
import com.study.banyiyi.entity.SysFileRelation;
import com.study.banyiyi.mapper.SysFileRelationMapper;
import com.study.banyiyi.util.FilesUtil;
import com.study.banyiyi.util.ResultMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * @ClassName UploadController
 * @Description 文件上传控制器
 * @Author yangwm
 * @Date 2021/6/24 22:19
 * @Version 1.0
 */
@RestController
@RequestMapping("/upload")
@PropertySource("classpath:app.properties")
public class UploadController {

    @Value("${upload.path}")
    private String realPath;

    @Autowired
    private SysFileRelationMapper mapper;

    /**
     * thymeleaf 模板访问传参
     * @return
     */
    @GetMapping("/goHome")
    public ModelAndView goHome(){
        ModelAndView mv = new ModelAndView("index");
        HashMap<String, Object> column = new HashMap<>();
        column.put("state","1");
        List<SysFileRelation> list = mapper.selectByMap(column);
        if(list!=null && list.size()>0){
            //返回已上传文件列表信息
            mv.addObject("list",list);
        }
        return mv;
    }


    /**
     * 文件上传保存
     * @param file
     * @return
     */
    @PostMapping("/saveFile")
    public ResultMsg saveUploadFile(@RequestParam("file")MultipartFile file) throws IOException {
        //第一步 判空
        if(file == null){
            return  new ResultMsg("500","上传文件不能为空！");
        }
        //第二步 将上传文件信息保存到数据库表中作为记录
        SysFileRelation fileRelation = SysFileRelation.builder()
                .fileId(UUID.randomUUID().toString().trim().replace("-",""))
                .fileName(file.getOriginalFilename())
                .filePath(realPath + "/" +file.getOriginalFilename())
                .fileUrl("http://localhost:9999/upload/saveFile")
                .fileSize((double) file.getSize())
                .fileType(file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(".")+1))
                .createTime(new SimpleDateFormat("yyyy-mm-dd HH:MM:SS").format(new Date()))
                .createUser("banyiyi")
                .state("1")
                .build();
        int i = mapper.insert(fileRelation);
        if(i <= 0){
            return new ResultMsg("500","数据库写入错误");
        }
        //第三步 将文件存储到服务地址中
        ResultMsg resultMsg = FilesUtil.simpleUploadFile(file, realPath);

        return  resultMsg;
    }

    /**
     * 根据文件id进行文件下载
     * @param fileId
     * @return
     */
    @GetMapping("/downloadFile")
    public ResultMsg downloadFile(@RequestParam("fileId") String fileId){
        //第一步 判断文件id是否为空
        if(StringUtils.isNullOrEmpty(fileId)){
            return new ResultMsg("204","下载文件的主键不能为空！");
        }
        //第二步 根据文件id查询文件相关信息
        SysFileRelation file = mapper.selectById(fileId);
        if(file ==null){
            return new ResultMsg("500","你所查找的文件不存在！");
        }
        //第三步 获取文件存放位置和名称
        try {
            String fileName = new String(file.getFileName().getBytes(),"utf-8");
            String filePath = file.getFilePath();
            ResultMsg resultMsg = FilesUtil.simpleDownloadData(filePath, fileName);
            return resultMsg;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


}
